;
(function(win) {

	JadeEngine.openWarnLog = false;

	//初始化画布
	var Snake = {};
	Snake.Canvas = {
		width: 20,
		height: 20,
		cols: 40,
		rows: 30
	}

	Snake.grids = [];

	Snake.init = function() {
		Snake.initWindow();
		Snake.initController();
		Snake.initSnake();
	}

	Snake.initWindow = function() {

		var canvas = document.getElementsByClassName("jade-grid-container")[0];

		var define = document.getElementsByClassName("define")[0];

		var defineCanvas = define.getElementsByClassName("jade-grid-container")[0];

		var gridView = defineCanvas.children[0];

		for (var row = 0; row < Snake.Canvas.rows; row++) {

			for (var col = 0; col < Snake.Canvas.cols; col++) {

				var grid = new JadeEngine.Grid(Snake.Canvas.width, Snake.Canvas.height);
				grid.x = col;
				grid.y = row;
				gridView.id = col + "_" + row;
				var style = "width:" + Snake.Canvas.width + "px;height:" + Snake.Canvas.height + "px;";
				style += "top:" + row * Snake.Canvas.width + "px;" + "left:" + col * Snake.Canvas.height + "px;";
				gridView.style = style;
				var child = document.createElement('div');
				child.innerHTML = gridView.outerHTML;
				grid.data = child.children[0];
				canvas.appendChild(grid.data);
				Snake.grids.push(grid)
			}

		}

	}

	Snake.renderBackground = function() {
		var control = Snake.controller;
		var layerGroup = control.currentScence.layerGroup;
		for (var row = 0; row < Snake.Canvas.rows; row++) {

			for (var col = 0; col < Snake.Canvas.cols; col++) {
				var render = layerGroup.getLocations(col,row)[0].grid.data;
				var style = render.style.cssText;
				style += ";background-color:black;";
				render.style = style;
			}
		}
	}

	Snake.layer = new JadeEngine.Layer(Snake.grids, "背景层", Snake.Canvas.cols, Snake.Canvas.rows);

	Snake.layerGroup = new JadeEngine.LayerGroup();

	Snake.layerGroup.addLayer(Snake.layer);

	Snake.sprite = new JadeEngine.Sprite("贪吃蛇", "");

	Snake.scene = new JadeEngine.Scene("默认场景", Snake.layerGroup, Snake.sprite);

	Snake.foodPool = [];

	Snake.hasFood = function(x, y) {
		if (Snake.foodPool.length == 0) {
			return false;
		}

		for (var i in Snake.foodPool) {
			var data = Snake.foodPool[i];
			if (data.x == x && data.y == y) {
				return true;
			}
		}
		return false;
	}

	Snake.scene.onEvent = function(context) {
		if (context.eventType == "second") {
			var control = Snake.controller;
			var layerGroup = control.currentScence.layerGroup;

			if (Snake.foodPool.length == 0) {
				var sprite = control.currentScence.sprites[0];
				var newPoint = function() {
					var point = Snake.randPointData(0, 0, Snake.Canvas.cols, Snake.Canvas.rows);

					if (point.x == sprite.x && point.y == sprite.y) {
						return newPoint();
					}
					return point;
				}

				var point = newPoint();
				Snake.renderFood(point);
			} else {
				Snake.renderFood(Snake.foodPool[0]);
			}
		}
	}

	Snake.renderFood = function(point) {
		Snake.foodPool = [];
		var control = Snake.controller;
		var layerGroup = control.currentScence.layerGroup;
		var render = layerGroup.getLocations(point)[0].grid.data;

		var style = render.style.cssText;
		style += ";background-color:red;";
		render.style = style;
		Snake.foodPool.push(point);
	}

	/**
	 * 随机整数，从start 开始，end结束
	 */
	Snake.randNum = function(start, end) {
		if (end <= start) {
			throw "随机数不正确！";
		}

		return Math.floor(Math.random() * end + start)
	}

	/**
	 * 随机点坐标
	 */
	Snake.randPointData = function(x, y, w, h) {
		var rx = Snake.randNum(x, w);
		var ry = Snake.randNum(y, h);
		return {
			"x": rx,
			"y": ry
		};
	}

	Snake.visibleWindow = new JadeEngine.VisibleWindow(Snake.scene, Snake.Canvas.cols, Snake.Canvas.rows);

	Snake.Body = function(point) {
		this.next = null;
		this.x = point.x;
		this.y = point.y;
		this.type = "head";
		this.direction = "down";
		this.count = 3;

		this.setDirection = function(direction) {
			if (direction == "down" && this.direction == "up") {
				return;
			}
			if (direction == "up" && this.direction == "down") {
				return;
			}
			if (direction == "left" && this.direction == "right") {
				return;
			}
			if (direction == "right" && this.direction == "left") {
				return;
			}
			this.direction = direction;
		}

		this.hasBody = function(x, y) {
			if (this.x == x && this.y == y) {
				return true;
			} else {
				if (this.next == null || typeof this.next === "undefined") {
					return false;
				}
				return this.next.hasBody(x, y);
			}
		}

		this.autoMove = function() {
			var data = {};
			data.x = this.x;
			data.y = this.y;
			switch (this.direction) {
				case "up":
					data.y = this.y - 1;
					break;
				case "down":
					data.y = this.y + 1;
					break;
				case "left":
					data.x = this.x - 1;
					break;
				case "right":
					data.x = this.x + 1;
					break;
			}

			if (Snake.hasFood(data.x, data.y)) {
				Snake.foodPool = [];
				Snake.sprite.data.last().next = new Snake.Body(data);
			}

			this.move(this);
			switch (this.direction) {
				case "up":
					this.y = this.y - 1;
					break;
				case "down":
					this.y = this.y + 1;
					break;
				case "left":
					this.x = this.x - 1;
					break;
				case "right":
					this.x = this.x + 1;
					break;
			}


		}
		this.move = function(point) {
			if (this.next) {
				this.next.move(this);
				this.next.x = this.x;
				this.next.y = this.y;
				this.x = point.x;
				this.y = point.y;
			}
		}

		this.append = function(next) {
			this.last().next = next;
			this.count + 1;
		}

		this.last = function() {
			if (this.next != null && typeof this.next !== "undefined") {
				return this.next.last();
			} else {
				return this;
			}
		}
	}

	Snake.initSnake = function() {
		Snake.sprite.data = new Snake.Body({
			x: 3,
			y: 2
		});

		Snake.sprite.data.last().next = new Snake.Body({
			x: 3,
			y: 1
		});

		Snake.sprite.data.last().next = new Snake.Body({
			x: 2,
			y: 1
		});
	}

	Snake.sprite.onEvent = function(context) {
		if (context.eventType == "minute") {

			var control = Snake.controller;
			var layerGroup = control.currentScence.layerGroup;
			var snake = Snake.sprite.data;
			var last = layerGroup.getLocations(snake.last())[0].grid.data;
			snake.autoMove();

			var grid = layerGroup.getLocations(snake)[0].grid;
			var head = grid.data;

			var headStyle = head.style.cssText;
			headStyle += ";background-color:navajowhite;";
			head.style = headStyle;

			var nextNode = snake.next;
			while (nextNode != null) {
				var body = layerGroup.getLocations(nextNode)[0].grid.data;
				var bodyStyle = body.style.cssText;
				bodyStyle += ";background-color:lightblue;";
				body.style = bodyStyle;
				nextNode = nextNode.next;
			}

			var lastStyle = last.style.cssText;
			lastStyle += ";background-color:black;";
			last.style = lastStyle;
		}
		if (context.eventType == "move") {
			Snake.sprite.data.setDirection(context.directionCode);
		}

	}

	Snake.controller = new JadeEngine.GameController(Snake.scene, Snake.sprite);

	Snake.initController = function() {
		var btnLeft = document.getElementsByClassName("jade-controller-left")[0];
		var btnRight = document.getElementsByClassName("jade-controller-right")[0];
		var btnUp = document.getElementsByClassName("jade-controller-up")[0];
		var btnDown = document.getElementsByClassName("jade-controller-down")[0];
		var btnStart = document.getElementsByClassName("jade-controller-start")[0];
		var btnStop = document.getElementsByClassName("jade-controller-stop")[0];
		var btnSuspend = document.getElementsByClassName("jade-controller-suspend")[0];
		var btnResume = document.getElementsByClassName("jade-controller-resume")[0];

		btnLeft.onclick = function() {
			Snake.controller.moveLeft();
		}

		btnRight.onclick = function() {
			Snake.controller.moveRight();
		}
		btnUp.onclick = function() {
			Snake.controller.moveUp();
		}

		btnDown.onclick = function() {
			Snake.controller.moveDown();
		}

		btnStart.onclick = function() {
			Snake.controller.start();
			console.log("开始游戏");
			Snake.renderBackground();
			Snake.initSnake();
		}

		btnStop.onclick = function() {
			Snake.controller.stop();
		}
		btnSuspend.onclick = function() {
			Snake.controller.suspend();
		}
		btnResume.onclick = function() {
			Snake.controller.resume();
		}

	}

	win.onload = function() {
		Snake.init();
	}

}(window));
